package com.chencs.common.grant.controller;

import com.alibaba.fastjson.JSON;
import com.chencs.common.grant.service.RoleService;
import com.chencs.vo.common.grant.RoleModel;
import framework.model.ResponseOptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by chencs on 2017/5/29.
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    Logger logger = LoggerFactory.getLogger(RoleController.class);

    @Autowired
    private RoleService roleService;

    @RequestMapping("/manager")
    public ModelAndView roleIndex() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("roleManager");
        return mv;
    }

        @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
        public String add(@RequestBody RoleModel model) {
            logger.info("access /role/add param = {}", JSON.toJSON(model));
            return  roleService.add(model);

    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public String update(@RequestBody RoleModel model) {
        logger.info("access /role/update param = {}", JSON.toJSON(model));
        roleService.update(model);
        return ResponseOptUtil.commonSucess();
    }


    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public String delete(@RequestBody RoleModel model) {
        logger.info("access /role/delete param = {}", JSON.toJSON(model));
        String  str = "";
        try {
            roleService.delete(model);
            str = ResponseOptUtil.commonSucess();
        }catch (Exception e){
            str = ResponseOptUtil.commonMsgError("删除角色失败");
        }
        return str;
    }

    @RequestMapping(value = "/get", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public String select(@RequestBody RoleModel model) {
        logger.info("access /role/select param = {}", model.getRoleID());
        RoleModel roleModel = null;
        try {
             roleModel =  roleService.findRoleById(model.getRoleID());
            if(roleModel==null){
                ResponseOptUtil.commonMsgError("角色不存在");
            }
        }catch (Exception e){
           return ResponseOptUtil.commonMsgError("查询角色失败");
        }
        return JSON.toJSON(roleModel).toString();
    }

    @RequestMapping(value = "/getList", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    public String getList() {
        return  JSON.toJSON( roleService.getList()).toString();
    }
}
